package cn.xeblog.plugin.tools.browser2.utils;

import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback;
import com.teamdev.jxbrowser.browser.callback.OpenPopupCallback;
import com.teamdev.jxbrowser.view.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

/**
 * @author eleven
 * @date 2024/11/18 9:17
 * @apiNote
 */
public class BrowserSettingUtil {
    public static void setPopupCallback(Browser browser, JPanel browserPanel, JTextField urlTextField) {
        browser.set(OpenPopupCallback.class, new OpenPopupCallback() {

            @Override
            public Response on(Params params) {
                Browser popupBrowser = params.popupBrowser();
                browserPanel.removeAll();
                browserPanel.add(BrowserView.newInstance(popupBrowser), BorderLayout.CENTER);
                setPopupCallback(popupBrowser,browserPanel,urlTextField);
                browserPanel.updateUI();
                return Response.proceed();
            }
        });
        browser.set(CreatePopupCallback.class, params -> {
            String targetUrl = params.targetUrl();
            urlTextField.setText(targetUrl);
            return CreatePopupCallback.Response.create();
        });
    }

    public static void setPopupCallback(Browser browser, JComponent component, JTextField urlTextField) {
        browser.set(OpenPopupCallback.class, new OpenPopupCallback() {

            @Override
            public Response on(Params params) {
                Browser popupBrowser = params.popupBrowser();
                component.removeAll();
                component.add(BrowserView.newInstance(popupBrowser), BorderLayout.CENTER);
                setPopupCallback(popupBrowser,component,urlTextField);
                component.updateUI();
                return Response.proceed();
            }
        });
        browser.set(CreatePopupCallback.class, params -> {
            String targetUrl = params.targetUrl();
            urlTextField.setText(targetUrl);
            return CreatePopupCallback.Response.create();
        });
    }
}
